package com.jspx.weixin.action;

import com.jspx.sioc.annotation.Ref;
import com.jspx.txweb.IUserSession;
import com.jspx.txweb.annotation.HttpMethod;
import com.jspx.txweb.annotation.Safety;
import com.jspx.txweb.dao.MemberDAO;
import com.jspx.txweb.env.TXWebIoc;
import com.jspx.txweb.online.OnlineManager;
import com.jspx.txweb.support.ActionSupport;
import com.jspx.utils.RandomUtil;
import com.jspx.utils.StringUtil;
import com.jspx.weixin.env.WeiXinEnv;
import com.jspx.weixin.table.WeiXinUser;
import org.weixin4j.*;
import org.weixin4j.component.SnsComponent;
import org.weixin4j.model.base.Token;

/**
 * 不会联动系统登陆信息，主要是构造微信的登陆连接请求
 * 请求后得到code
 */
@HttpMethod(caption = "微信验证请求")
public class WeiXinLoginAction extends ActionSupport {

    private  final static String authorize_url = "https://open.weixin.qq.com/connect/oauth2/authorize";
    //这个地址为  WeiXinOAuth2Action 的路径
    //这个地址发送给微信,微信将数据传输到这个地址上
    private String redirectUrl = StringUtil.empty;
    @Safety(request = false)
    public void setRedirectUrl(String redirectUrl) {
        this.redirectUrl = redirectUrl;
    }

    // snsapi_base 只能获取用户openid,snsapi_userinfo 可以得到用户信息
    private String scope = "snsapi_userinfo"; //snsapi_userinfo
    @Safety(request = false)
    public void setScope(String scope) {
        this.scope = scope;
    }

    //如果用户已经登陆到，就直接跳转到这里地址
    private String loginUrl =  StringUtil.empty;
    @Safety(request = false)
    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }

    private boolean loinJump =  false;
    @Safety(request = false)
    public void setLoinJump(boolean loinJump) {
        this.loinJump = loinJump;
    }

    protected OnlineManager onlineManager;
    @Ref(name = TXWebIoc.onlineManager)
    public void setOnlineManager(OnlineManager onlineManager) {
        this.onlineManager = onlineManager;
    }

    @Override
    public String execute() throws Exception {
        IUserSession userSession = onlineManager.getUserSession(this);
        if (loinJump&&userSession!=null&&!userSession.isGuest())
        {
            response.sendRedirect(loginUrl);
        }
        else
        {
            Weixin weinxin = WeixinBuilder.newInstance().build();
            SnsComponent snsComponent = weinxin.sns(authorize_url);
            String state = RandomUtil.getRandomAlphanumeric(12);
            //为了防止攻击 state 为随机数，接受回来验证
            session.setAttribute(WeiXinEnv.weiXinState,state);
            session.setAttribute(WeiXinEnv.weiXinScope,scope);
            String url = snsComponent.getOAuth2CodeUrl(redirectUrl,scope,state);
            response.sendRedirect(url);
        }
        return NONE;
    }

}
